package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.HealthManagerDao;
import com.itheima.dao.MemberDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.*;
import com.itheima.service.MemberService;
import com.itheima.utils.BrithdayUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private HealthManagerDao healthManagerDao;
    @Autowired
    private SetmealDao setmealDao;

    /**
     * 根据手机号查询会员信息
     *
     * @param telephone
     * @return
     */
    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    /**
     * 会员注册
     *
     * @param member
     */
    @Override
    public void add(Member member) {
        //对会员密码加密
        String password = member.getPassword();
        if (password != null) {
            //随机获取5位随机码
            String salt = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
            member.setSalt(salt);
            //对密码加盐加密
            password = MD5Utils.md5(salt + password);
            member.setPassword(password);
        }
        memberDao.add(member);
    }

    /**
     * 通过日期统计会员数量
     *
     * @param list
     * @return
     */
    @Override
    public List<Integer> findMemberCountByMonth(List<String> list) {
        List<Integer> memberCounts = new ArrayList<>();
        for (String month : list) {
            month = month + ".31";
            //统计会员
            Integer memberCount = memberDao.findMemberCountBeforeDate(month);
            memberCounts.add(memberCount);
        }
        return memberCounts;
    }

    /**
     * 预约订单修改
     *
     * @param member
     */
    @Override
    public void updateMember(Member member) {
        memberDao.updateMember(member);
    }

    /**
     * 修改会员的个人信息
     *
     * @param member
     */
    @Override
    public void edit(Member member) {
        memberDao.edit(member);
    }

    @Override
    public List<Map> findOrderByDate(Map<String, Object> map) {
        return memberDao.findOrderByDate(map);
    }

    //年龄分布统计
    @Override
    public Map<String, Object> findAgeGroup() {
        //封装年龄段名称和数量
        Map<String, Object> map = new HashMap<>();
        //接收年龄段名称
        List<String> ageGroups = new ArrayList<>();
        //接收年龄段对应的数量
        List<Integer> numbers = new ArrayList<>();
        //调用dao层获取年龄段和数量
        List<Map<String, Object>> list = memberDao.ageGroup();
        for (Map<String, Object> sMap : list) {
            String ageGroup1 = (String) sMap.get("ageGroup");
            ageGroups.add(ageGroup1);
            Long number = (Long) sMap.get("number");
            numbers.add(Math.toIntExact(number));
        }
        map.put("ageGroups", ageGroups);
        map.put("numbers", numbers);
        return map;
    }

    //-------------------------会员
    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //获取参数
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        Integer currentPage = queryPageBean.getCurrentPage();
        //将参数交由分页助手处理
        PageHelper.startPage(currentPage, pageSize);
        //根据搜索条件进行查询
        Page<Member> page = memberDao.findPage(queryString);
        //给healthManager赋值
//        for (Member member : page) {
//            Integer id = member.getId();
//            HealthManager healthManager = healthManagerDao.findHealthManagerById(id);
//            if (healthManager != null) {
//                String name = healthManager.getName();
//                member.setHealthManager(name);
//            }
//        }
        //获得总条目数
        long total = page.getTotal();
        //获得当页结果
        List<Member> rows = page.getResult();
        //创建返回对象携带数据到控制层
        PageResult pageResult = new PageResult(total, rows);
        return pageResult;
    }

    //后台添加会员
    public void backendAdd(Member member) throws Exception {
        member.setRegTime(new Date());
        Integer date1 = BrithdayUtils.getBrithday(member.getBirthday());  //2020
        Integer date2 = BrithdayUtils.getBrithday(new Date());
        Integer brithday = date2 - date1;
        member.setAge(brithday);
        memberDao.add(member);
        //判断是否选择了健康管理师
//        String healthManagerName = member.getHealthManager();
//        Integer id = member.getId();
//        if (healthManagerName != null) {
//            HealthManager healthManager = new HealthManager();
//            healthManager.setMember_id(id);
//            healthManager.setName(healthManagerName);
//            healthManagerDao.add(healthManager);
//        }
    }

    @Override
    public void deleteById(Integer id) {
        long count = memberDao.findMemberOrderById(id);
        long number = memberDao.findMemberHealthManagerById(id);
        if (count > 0 || number > 0) {
            throw new RuntimeException("你选择得会员已绑定其他信息,无法删除");
        }
        memberDao.deleteById(id);
    }

    @Override
    public void editMember(Member member) throws Exception {
        Integer date1 = BrithdayUtils.getBrithday(member.getBirthday());  //2020
        Integer date2 = BrithdayUtils.getBrithday(new Date());
        Integer brithday = date2 - date1;
        member.setAge(brithday);
        memberDao.update(member);
//        String healthManagerName = member.getHealthManager();
//        Integer id = member.getId();
//        if (healthManagerName != null) {
//            HealthManager healthManager = new HealthManager();
//            healthManager.setMember_id(id);
//            healthManager.setName(healthManagerName);
//            healthManagerDao.update(healthManager);
//        }
    }

    //数据回显查询
    @Override
    public Member findById(Integer id) {
        Member member = memberDao.findById(id);
//        if (member.getHealthManager()!=null){
//            HealthManager healthManager = healthManagerDao.findHealthManagerById(id);
//            String healthManagerName = healthManager.getName();
//            member.setName(healthManagerName);
//        }
        return member;
    }

    @Override
    public List<HealthManager> findDate() {
        List<HealthManager> list = healthManagerDao.findAll();
        return list;
    }

    @Override
    public List<Map> getReportData(Integer[] ids) {
        List<Map> list = new ArrayList<>();
        for (Integer id : ids) {
            List<String> addressName = new ArrayList<>();
            List<String> setmealName = new ArrayList<>();
            List<String> checkGroupName = new ArrayList<>();
            List<String> checkItem = new ArrayList<>();
            Map<String, Object> result = new HashMap<>();
            Member member = memberDao.findById(id);
            String name = member.getName();
            String sex = member.getSex();
            String phoneNumber = member.getPhoneNumber();
            result.put("name", name);    //会员名字
            if (sex!=null){
                if (sex.equals("1")) {
                    sex = "男";
                } else {
                    sex = "女";
                }
            }
            result.put("sex", sex);      //会员性别
            result.put("phoneNumber", phoneNumber);  //会员手机号
            //获取表t_address的id
            List<Integer> addressId = memberDao.findAddressIdByMemberId(id);
            //获取多个地址
            if (addressId != null && addressId.size() > 0) {
                for (Integer integer : addressId) {
                    List<String>  address = memberDao.findAddress(integer);
                    for (String Name : address) {
                        addressName.add(name);
                    }
                }
            }
            //套餐信息
//            List<Setmeal> setmeals = memberDao.findSetmeal(id);

//            if (setmeals != null && setmeals.size() > 0) {
//                for (Setmeal setmeal : setmeals) {
//                    String string = setmeal.getName();
//                    setmealName.add(string);
//                    Integer setmealId = setmeal.getId();
//                    List<CheckGroup> checkGroups = memberDao.findCheckgroup(setmealId);
//                    if (checkGroups != null && checkGroups.size() > 0) {
//                        for (CheckGroup checkGroup : checkGroups) {
//                            String GroupName = checkGroup.getName();
//                            checkGroupName.add(GroupName);
//                            Integer checkGroupId = checkGroup.getId();
//                            List<String> checkItemName = memberDao.findCheckItemName(checkGroupId);
//                            if (checkItemName != null && checkGroupName.size() > 0) {
//                                for (String s : checkGroupName) {
//                                    checkItem.add(s);
//                                }
//                            }
//                        }
//                    }
//
//                }
//            }
            List<Integer> setmealId = memberDao.findSetmealId(id);
            if (setmealId != null && setmealId.size() > 0) {
                for (Integer sid : setmealId) {
                    //根据套餐ID查询套餐详细信息（包括套餐基本信息、套餐包含的检查组、检查组包含的检查项）
                    Setmeal setmeal = setmealDao.findSetmealById(sid);
                    String Name = setmeal.getName();
                    setmealName.add(Name);
                    List<CheckGroup> checkGroups = setmeal.getCheckGroups();
                    for (CheckGroup checkGroup : checkGroups) {
                        String checkGroupName1 = checkGroup.getName();
                        checkGroupName.add(checkGroupName1);
                        List<CheckItem> checkItems = checkGroup.getCheckItems();
                        for (CheckItem item : checkItems) {
                            String name1 = item.getName();
                            checkItem.add(name1);
                        }
                    }
                }
            }
            result.put("address", addressName);  //预约地址
            result.put("setmealName", setmealName);//套餐信息名字集合
            result.put("checkGroupName", checkGroupName); //检查组名字集合
            result.put("checkItemName", checkItem);//检查项名字集合
            list.add(result);
        }
       // System.out.println(list);
        return list;
    }
}
